package com.ruoyi.system.controller;




import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.web.domain.AjaxResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/wechatLogin")
public class WechatAppLonginController {

    /**
     * 微信小程序AppID
     */
    private final static String AppID = "wx7051e17c945a1f97";
    /**
     * 微信小程序AppSecret
     */
    private final static String AppSecret = "265345b035fc65ec44a709f2e3b69f2d";


    @GetMapping("/wxlogin")
    public AjaxResult getWechatLoginInfo(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, code);
        String result = HttpUtil.get(url + "?" + params);
        JSONObject jsonObject = JSONObject.parseObject(result);

        Object session_key = jsonObject.get("session_key").toString();
        String openid =jsonObject.get("openid").toString();
        if (StrUtil.isEmpty(openid)) {
            return AjaxResult.error("未获取到openid");
        }
        String token = UUID.randomUUID().toString();
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("session_key", session_key);
        data.put("openid", openid);
        return AjaxResult.success(data);
    }







}
